package com.example.yunifang.dao;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.yunifang.bean.GouWuCheBean;
import com.example.yunifang.db.GouWuCheOpenHelper;

public class GouWuCheDao {
	private GouWuCheOpenHelper helper;

	public GouWuCheDao(Context context) {
		helper = new GouWuCheOpenHelper(context);
	}
	//添加
	public void add(GouWuCheBean bean) {
		SQLiteDatabase db = helper.getWritableDatabase();
		if (query(bean) != null) {
			GouWuCheBean b = query(bean);
			String id = b.getShop_id();
			int num = b.getNum();
			if (bean.getShop_id().equals(id)) {
				update((bean.getNum() + num), id);
			}
		} else {
			ContentValues values = new ContentValues();
			values.put("name", bean.getName());
			values.put("img", bean.getImg());
			values.put("price", bean.getPrice());
			values.put("shop_id", bean.getShop_id());
			values.put("num", bean.getNum());
			db.insert("gouwuche", null, values);
		}
		db.close();
	}
	//根据商品id查询
	public GouWuCheBean query(GouWuCheBean b) {
		GouWuCheBean bean = null;
		SQLiteDatabase db = helper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select * from gouwuche where shop_id=?",
				new String[] { b.getShop_id() });
		while (cursor.moveToNext()) {
			String id = cursor.getString(cursor.getColumnIndex("shop_id"));
			int num = cursor.getInt(cursor.getColumnIndex("num"));
			GouWuCheBean g=new GouWuCheBean();
			g.setShop_id(id);
			g.setNum(num);
			bean=g;
		}
		return bean;
	}
	//修改
	public void update(int count, String id) {
		SQLiteDatabase db = helper.getWritableDatabase();
		db.execSQL("update gouwuche set num=? where shop_id=?", new Object[] {
				count, id });
		db.close();
	}
	//全部查询
	public ArrayList<GouWuCheBean> quaryAll() {
		ArrayList<GouWuCheBean> data = new ArrayList<GouWuCheBean>();
		SQLiteDatabase db = helper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select * from gouwuche", null);
		while (cursor.moveToNext()) {
			String name = cursor.getString(cursor.getColumnIndex("name"));
			String img=cursor.getString(cursor.getColumnIndex("img"));
			float price=cursor.getFloat(cursor.getColumnIndex("price"));
			String id=cursor.getString(cursor.getColumnIndex("shop_id"));
			int num=cursor.getInt(cursor.getColumnIndex("num"));
			GouWuCheBean bean=new GouWuCheBean(img, price, num, id, name);
			data.add(bean);
		}
		cursor.close();
		db.close();
		return data;
	}
	//删除
	public void delete(ArrayList<String> id){
		SQLiteDatabase db = helper.getWritableDatabase();
		for(String s:id){
			db.delete("gouwuche", "shop_id=?", new String[]{s});
		}
		db.close();
	}

}
